package com.foolishbird.sdk.assist;

import android.app.Activity;
import android.os.AsyncTask;
import android.text.TextUtils;


import com.alipay.sdk.app.PayTask;
import com.foolishbird.sdk.params.bean.AlipayResult;
import com.foolishbird.sdk.utils.WL;

import java.util.Map;

/**
 * Created by Administrator on 2017/6/9 0009.
 */

public class AlipayPayOperation extends AsyncTask<String, Integer, AlipayResult> {

    private static final String TAG = AlipayPayOperation.class.getSimpleName();

    private final Activity activity;

    public AlipayPayOperation(Activity activity) {
        if (activity == null) {
            throw new IllegalArgumentException("AlipayPayOperation activity can not be initialized with null");
        }
        this.activity = activity;
    }

    @Override
    protected AlipayResult doInBackground(String... params) {
        Map<String, String> result = new PayTask(activity).payV2(params[0], true);
        return new AlipayResult(result);
    }

    @Override
    protected void onPostExecute(AlipayResult result) {
        super.onPostExecute(result);
        if (result.isPaySuccess()) {
            CallbackObservable observable = CallbackObservable.getInstance();
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, "alipay pay state is success", null);
            WL.d(TAG, "alipayPayV2 is success.");
        } else if (TextUtils.equals(result.getResultStatus(), "6001")) {
            CallbackObservable observable = CallbackObservable.getInstance();
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, "alipay pay state is cancel", null);
            WL.d(TAG, "alipayPayV2 is state is cancel.");
        } else if (TextUtils.equals(result.getResultStatus(), "8000") || TextUtils.equals(result.getResultStatus(), "6004")) {
            CallbackObservable observable = CallbackObservable.getInstance();
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_UNKNOWN, "alipay pay state is unknown", null);
            WL.d(TAG, "alipayPayV2 is success.");
        } else {
            CallbackObservable observable = CallbackObservable.getInstance();
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_FAILED, "alipay pay state is failed", null);
            WL.d(TAG, "alipayPayV2 is failed. errorResult: " + result.toString());
        }
        activity.finish();
    }
}
